package ygstudio.xue.de.list;

import java.util.ArrayList;

import ygstudio.xue.de.R;
import ygstudio.xue.de.db.DB;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListAdapter extends ArrayAdapter<BaseData> {

	private final Context context;
	private final ArrayList<BaseData> baseDataList;
	private int selectedIndex = -1;

	public int getSelectedIndex() {
		return selectedIndex;
	}

	public void setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
	}

	public ListAdapter(Context context, ArrayList<BaseData> baseDataList) {

		super(context, R.layout.list_item, baseDataList);

		this.context = context;
		this.baseDataList = baseDataList;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// 1. Create inflater
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// 2. Get rowView from inflater
		View rowView = null;
		rowView = inflater.inflate(R.layout.list_item, parent, false);

		if (selectedIndex == position) {
			rowView.setBackgroundResource(R.color.selected);
		}
		BaseData baseData = baseDataList.get(position);

		// 3. Get icon,title & counter views from the rowView
		ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
		TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
		TextView counterView = (TextView) rowView
				.findViewById(R.id.item_counter);

		String dbTable = baseData.getDbTable();
		if (dbTable.equalsIgnoreCase(DB.TABLE_SATZ)) {
			titleView.setText(Html.fromHtml(baseData.getValueOf(DB.F_DE))
					.toString());
			imgView.setImageResource(R.drawable.satz);
		} else {
			titleView.setText(baseData.getValueOf(DB.F_TITLE));
		}

		if (dbTable.equalsIgnoreCase(DB.TABLE_TEXT)) {
			imgView.setImageResource(R.drawable.document);
		} else if (dbTable.equalsIgnoreCase(DB.TABLE_WORT)) {
			imgView.setImageResource(R.drawable.word);
		}

		TextView ratingView = (TextView) rowView.findViewById(R.id.item_rating);
		String rating = baseData.getValueOf(DB.F_RATING);
		
		if (rating == null || rating.isEmpty()) {

		} else {
			float f = Float.parseFloat(rating);
			String rText = "";
			for (int i = 0; i <f; i++) {
				rText += "\u2605";
			}
			ratingView.setText(rText);
		} 
		counterView.setText(baseData.getValueOf(DB.F_COUNT));
		return rowView;
	}

}